package com.health.commons;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

public class CommonsUtils {

	public static String getDateTimeByFmt(String fmt) {
		Date nowTime = new Date();
		SimpleDateFormat time = new SimpleDateFormat(fmt);
		return time.format(nowTime);
	}

	public static String genRandomCode() {
		String randomCode = "";

		Random random = new Random(System.currentTimeMillis());
		long number = (long) (Math.abs(random.nextGaussian()) * 1000000);
		randomCode = String.format("%06d", number).substring(0, 6);

		return randomCode;
	}

	public static String getFormatMDN(String mdn) {
		if (null != mdn && mdn.length() > 11) {
			mdn = mdn.substring(mdn.length() - 11);
		}
		return mdn;
	}

	public static long[] RandomSplitLong(int size, long total) {
		long[] percent = new long[size];
		long min = total / (size * 5);
		System.out.println("min:" + min);
		Arrays.fill(percent, min);
		long surplus = total - size * min;
		System.out.println("surplus:" + surplus);
		int step = min > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) min;

		Random r = new Random();
		while (surplus > 0) {
			int index = r.nextInt(size);
			long diff = r.nextInt(step) + min;
			if (surplus < diff)
				diff = surplus;
			percent[index] += diff;
			surplus -= diff;
		}
		return percent;
	}

	public static Object genBeanByJson(String strJson, Class<?> claz) {
		Object bean = null;
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
		objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
		try {
			bean = objectMapper.readValue(strJson, claz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bean;
	}

	public static void dumpObject(Logger logger, Object obj) {
		ObjectMapper om = new ObjectMapper();
		try {
			om.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
			om.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
			om.setSerializationInclusion(Inclusion.NON_NULL); 
			logger.debug(om.writeValueAsString(obj));
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String dumpObject(Object obj) {
		ObjectMapper om = new ObjectMapper();
		om.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
		om.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

		try {
			return om.writeValueAsString(obj);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发�?Get请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static byte[] httpGet(String url, List<NameValuePair> params) {
		byte[] body = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			// Get请求
			HttpGet httpget = new HttpGet(url);
			// httpget.addHeader("Content-Type",
			// "application/application/json; charset=utf-8");

			// 设置参数
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
			httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
			System.out.println(httpget.getURI());
			// 发�?请求
			HttpResponse httpresponse = httpClient.execute(httpget);

			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			// body = EntityUtils.toString(entity);

			body = EntityUtils.toByteArray(entity);

			if (entity != null) {
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static byte[] httpPut(String url, String json) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		byte[] body = null;
		try {
			HttpPut putRequest = new HttpPut(url);
			putRequest.addHeader("Content-Type", "application/json");
			putRequest.addHeader("Accept", "application/json");
			StringEntity input = new StringEntity(json, "UTF-8");
			putRequest.setEntity(input);
			HttpResponse response = httpClient.execute(putRequest);
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
			}
			HttpEntity entity = response.getEntity();
			body = EntityUtils.toByteArray(entity);

			if (entity != null) {
				entity.consumeContent();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	/**
	 * 发�?Get请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static byte[] httpDelete(String url, List<NameValuePair> params) {
		byte[] body = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			// DELETE请求
			HttpDelete httpDel = new HttpDelete(url);
			// httpget.addHeader("Content-Type",
			// "application/application/json; charset=utf-8");

			// 设置参数
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
			httpDel.setURI(new URI(httpDel.getURI().toString() + "?" + str));
			System.out.println(httpDel.getURI());
			// 发�?请求
			HttpResponse httpresponse = httpClient.execute(httpDel);

			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			// body = EntityUtils.toString(entity);

			body = EntityUtils.toByteArray(entity);

			if (entity != null) {
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return body;
	}

	/**
	 * 发�?Get请求
	 * 
	 * @param url
	 * @return
	 */
	public static byte[] httpGet(String url) {
		byte[] body = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			// Get请求
			HttpGet httpget = new HttpGet(url);
			// 发�?请求
			HttpResponse httpresponse = httpClient.execute(httpget);
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toByteArray(entity);

			if (entity != null) {
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return body;
	}

	public static String getContentCharSet(final HttpEntity entity) {

		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) {
					charset = param.getValue();
				}
			}
		}

		if (null == charset || charset.isEmpty()) {
			charset = "UTF-8";
		}
		return charset;
	}

	public static byte[] httpPost(String uri, String data) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(uri);
		byte[] body = null;
		try {
			HttpParams params = client.getParams();
			HttpConnectionParams.setConnectionTimeout(params, 10000);

			StringEntity strEntity = new StringEntity(data, "UTF-8");
			strEntity.setContentEncoding("UTF-8");
			strEntity.setContentType("application/json");

			post.setEntity(strEntity);
			HttpResponse response = client.execute(post);

			HttpEntity entity = response.getEntity();
			body = EntityUtils.toByteArray(entity);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			client.getConnectionManager().shutdown();
		}

		return body;
	}

	public static String httpClientPost(String uri, String data) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(uri);
		System.out.println("POST URL=" + uri);
		String responseBuffer = null;
		try {
			HttpParams params = client.getParams();
			HttpConnectionParams.setConnectionTimeout(params, 10000);

			StringEntity strEntity = new StringEntity(data);
			strEntity.setContentEncoding("UTF-8");
			strEntity.setContentType("application/x-www-form-urlencoded");

			post.setEntity(strEntity);
			HttpResponse response = client.execute(post);

			responseBuffer = EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			client.getConnectionManager().shutdown();
		}

		return responseBuffer;
	}

	public static List<String> getDatesBetween(String begin, String end) {
		List<String> dates = new ArrayList<String>();

		try {
			String beginString = begin.substring(0, 10);
			String endString = end.substring(0, 10);

			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

			String dateString = beginString;
			while (0 >= dateString.compareTo(endString)) {
				dates.add(dateString);

				Date baseDate = dateFormat.parse(dateString);
				Date date = new Date(baseDate.getTime() + 24 * 60 * 60 * 1000);
				dateString = dateFormat.format(date);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dates;
	}

	public static boolean isEmpty(String str) {
		return (null == str || str.isEmpty());
	}

	public static boolean isEmpty(Integer str) {
		return (null == str );
	}
	 
	public static <T> List<T> getRandomFromList(List<T> l, int returnSize) {
		if (returnSize > l.size()) {
			returnSize = l.size();
		}
		Collections.shuffle(l);
		return l.subList(0, returnSize);
	}

	/**
	 * 发�?Get请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static byte[] httpPost(String url, List<NameValuePair> params) {
		byte[] body = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			// POST请求
			HttpPost httpPost = new HttpPost(url);
			// 设置参数
			HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(httpEntity);

			HttpResponse httpresponse = httpClient.execute(httpPost);
			// 获取返回数据
			HttpEntity entity = httpresponse.getEntity();
			body = EntityUtils.toByteArray(entity);
			if (entity != null) {
				entity.consumeContent();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return body;
	}

	/**
	 * 文字�?6进制
	 * 
	 * @param s
	 */
	public static void String2Hex(String s) {
		byte[] b = s.getBytes();
		for (int i = 0; i < b.length; i++) {
			int row = i / 16;// �?
			int col = i % 16;// �?
			if (col == 0)// 行头
				System.out.print(getLineHead(row));
			System.out.print(Integer.toHexString(b[i] & 0xFF) + " ");
			if (col == 15 || i == b.length - 1)// 行尾
				System.out.println(getLineTail(b, row * 16, i % 16 + 1));
		}
	}

	/**
	 * 得到行头
	 * 
	 * @param k
	 *            当前行数
	 * @return
	 */
	private static String getLineHead(int k) {
		String head = "000000";
		head += Integer.toHexString(k) + "0h: ";
		if (head.length() > 11)
			return head.substring(head.length() - 11, head.length());
		else
			return head;
	}

	/**
	 * 得到行尾
	 * 
	 * @param b
	 *            字节数组
	 * @param off
	 *            偏移位置
	 * @param len
	 *            长度
	 * @return
	 */
	private static String getLineTail(byte[] b, int off, int len) {
		StringBuffer tail = new StringBuffer();
		for (int i = 0; i < 16 - len; i++)
			tail.append("   ");
		tail.append("; " + new String(b, off, len));
		return tail.toString();
	}

	public static void main(String[] args) {
		System.out.println(getFormatMDN("1390"));
		System.out.println(getFormatMDN(""));
		System.out.println(getFormatMDN(null));
		System.out.println(getFormatMDN("13901321264"));
		System.out.println(getFormatMDN("8613901321264"));
		System.out.println(getFormatMDN("+8613901321264"));
	}
}
